package com.tcoiss.webservice.service.impl;

import com.tcoiss.common.core.enums.ErroEnums;
import com.tcoiss.common.core.exception.CustomException;
import com.tcoiss.common.core.utils.StringUtils;
import com.tcoiss.common.core.web.domain.AjaxResult;
import com.tcoiss.common.component.api.model.GaodePoiVo;
import com.tcoiss.common.component.api.model.GdAdminDivisionVo;
import com.tcoiss.webservice.domain.*;
import com.tcoiss.webservice.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 朱圣煌
 * 创建时间 2021-08-05
 */
@Service
@Slf4j
public class GaodeApiServiceImpl  implements IGaodeApiService {

    @Autowired
    private IApiService iApiService;

    @Override
    public Map<String,Object> getDistrictsIdByNumber(String location){
        if(StringUtils.isEmpty(location)){
            throw new CustomException(ErroEnums.BUSERRO.getCode(), new String[]{"参数为:" + location},ErroEnums.BUSERRO.getInfo() + "参数不合法，参数不能为空");
        }
        log.info("传入的经纬度是: " + location);
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("location", URLEncoder.encode(location, "utf-8"));
            map.put("key", "a33e36c0e15b373a2ebd7fc4aa1ec0c2");
            Map<String, Object> resultMap = iApiService.executeByApiCode("getAddressByLocation", map);
            if (resultMap == null) {
                throw new CustomException(ErroEnums.APIERRO.getCode(), new String[]{"传入的经纬度是: " + location}, ErroEnums.APIERRO.getInfo() + "获取地址坐标请求连接异常");
            }
            //成功
            if (Integer.parseInt(resultMap.get("status").toString()) == 1) {
                Map<String, Object> regeocode = (Map<String, Object>) resultMap.get("regeocode");
                Map<String, Object> addressMap = (Map<String, Object>) regeocode.get("addressComponent");
                return  addressMap;
            } else {
                throw new CustomException(ErroEnums.APIERRO.getCode(), null, ErroEnums.APIERRO.getInfo() + "高德返回状态为:" + resultMap.get("info") + "。高德无法解析该坐标,请重新检查坐标");
            }
        } catch (Exception e) {
            throw new CustomException(ErroEnums.SYSERRO.getCode(), "系统异常",e);
        }
    }


    @Override
    public AjaxResult queryLocations(AddressKeyVo address) {
        Map<String,Object> params = new HashMap<>();
        params.put("key","fc192adf62dc818ffe64fbcc68dfadd1");
        if(address==null||address.getAddress()==null){
            // AjaxResult.error(205,"获取地址列表错误：请求参数不合法");
            return AjaxResult.error(ErroEnums.APIERRO.getCode(), "获取地址列表错误：请求参数不合法");
        }
        params.put("keywords",address.getAddress());
        if(address.getCity()!=null&&!address.getAddress().isEmpty()){
            params.put("city",address.getCity());
        }
        //通过地址关键字查询地址列表
        Map<String,Object> result = iApiService.executeByApiCode("queryAddress",params);
        if(result == null){
            return AjaxResult.error(ErroEnums.APIERRO.getCode(),"获取地址列表错误：http请求连接异常");
        }else {
            //创建成功
            if (Integer.valueOf(result.get("status").toString()) == 1) {
                List<Map<String, Object>> pois = (List<Map<String, Object>>) result.get("pois");
                int count = Integer.valueOf(result.get("count").toString());
                if(count==0){
                    List list = new ArrayList();
                    return AjaxResult.success("成功",list);
                }
                List<GaodePoiVo> vos = new ArrayList<>();
                for(Map<String,Object> poi:pois){
                    GaodePoiVo vo = new GaodePoiVo();
                    try {
                        BeanUtils.populate(vo, poi);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                        return AjaxResult.success("系统异常");
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                        return AjaxResult.error("系统异常");
                    }
                    vos.add(vo);
                }
                return AjaxResult.success("成功",vos);
            }else{
                return AjaxResult.error(ErroEnums.APIERRO.getCode(),"获取地址列表异常："+result.get("info").toString());
            }
        }
    }

    public List<Map<String, Object>> queryAdminDivision(){
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("keywords", URLEncoder.encode("江西省", "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new CustomException(ErroEnums.SYSERRO.getCode(), "系统异常",e);
        }
        map.put("subdistrict", 3);
        map.put("extensions", "base");
        map.put("key", "fc192adf62dc818ffe64fbcc68dfadd1");
        // 请求行政区划获取第四级地址与名称
        Map<String, Object> resultMap = iApiService.executeByApiCode("getDistrictInfo", map);
        if (resultMap == null) {
            throw new CustomException(ErroEnums.APIERRO.getCode(),null,ErroEnums.COMERRO.getInfo() + "获取地址坐标请求连接异常");
        } else {
            //成功
            if (Integer.parseInt(resultMap.get("status").toString()) == 1) {
                //redisService.setCacheList("gaode", excelVos);
                return (List<Map<String, Object>>)resultMap.get("districts");
            }
        }
        return null;
    }

    @Override
    public List<GdAdminDivisionVo> getDistrictInfo() {
        List<Map<String, Object>> province = queryAdminDivision();
        // 获取江西省
        if(province!=null){
            List<GdAdminDivisionVo> gdAdminDivisions = new ArrayList<>();
            for (int i = 0; i < province.size(); i++) {
                Map<String, Object> provinceCode = province.get(0);
                GdAdminDivisionVo gdProvince = new GdAdminDivisionVo();
                gdProvince.setNumber((String) provinceCode.get("adcode"));
                gdProvince.setName((String) province.get(i).get("name"));
                gdProvince.setAdministrativeLevelsId(1L);
                gdProvince.setIsCity("true");
                gdProvince.setFullName(province.get(i).get("name").toString());
                gdProvince.setStatus("C");
                gdProvince.setEnable("1");
                gdAdminDivisions.add(gdProvince);
                // 获取所有市级
                List<Map<String, Object>> city = (List<Map<String, Object>>) province.get(i).get("districts");
                for (int j = 0; j < city.size(); j++) {
                    GdAdminDivisionVo gdCity = new GdAdminDivisionVo();
                    gdCity.setNumber((String) city.get(j).get("city"));
                    gdCity.setName((String) city.get(j).get("name"));
                    gdCity.setAdministrativeLevelsId(2L);
                    gdCity.setParent(gdProvince.getNumber());
                    gdCity.setIsCity("true");
                    gdCity.setFullName(gdProvince.getName()+"_"+city.get(j).get("name").toString());
                    gdCity.setStatus("C");
                    gdCity.setEnable("1");
                    gdAdminDivisions.add(gdCity);
                    // 获取当前市的区县
                    List<Map<String, Object>> district = (List<Map<String, Object>>) city.get(j).get("districts");
                    for (int k = 0; k < district.size(); k++) {
                        GdAdminDivisionVo gdDistrict = new GdAdminDivisionVo();
                        gdDistrict.setNumber((String) district.get(k).get("adcode"));
                        gdDistrict.setName((String) district.get(k).get("name"));
                        gdDistrict.setParent(gdCity.getNumber());
                        gdDistrict.setAdministrativeLevelsId(3L);
                        gdDistrict.setIsCity("true");
                        gdDistrict.setFullName(gdCity.getFullName()+"_"+district.get(k).get("name").toString());
                        gdDistrict.setStatus("C");
                        gdDistrict.setEnable("1");
                        gdAdminDivisions.add(gdDistrict);
                        // 获取当前区县的乡镇
                        List<Map<String, Object>> towns = (List<Map<String, Object>>) district.get(k).get("districts");
                        for(Map<String, Object> town:towns){
                            GdAdminDivisionVo gdTown = new GdAdminDivisionVo();
                            gdTown.setNumber("");
                            gdTown.setName((String) town.get("name"));
                            gdTown.setAdministrativeLevelsId(4L);
                            gdTown.setParent(gdDistrict.getNumber());
                            gdTown.setIsCity("true");
                            gdTown.setFullName(gdDistrict.getFullName()+"_"+town.get("name").toString());
                            gdTown.setStatus("C");
                            gdTown.setEnable("1");
                            gdAdminDivisions.add(gdTown);
                        }
                    }
                }
            }
            return gdAdminDivisions;
        }

        return null;
    }

}
